<template>
    <van-list
        v-model:loading="loading"
        v-model:error="error"
        :error-text="errorText"
        :finished="finished"
        @load="onLoad"
        class="GameServerList"
    >
        <van-pull-refresh
            v-model="loading"
            success-text="刷新成功"
            @refresh="onLoad"
        >
            <van-cell
                v-for="item in list"
                :key="item"
                :title="item.serverName"
                is-link
                @click="onSelectedServer(item)"
            >
                <van-tag plain type="success"
                    >{{ item.clientCount }} 人在线</van-tag
                >
            </van-cell>
            <van-empty v-if="!list || list.length==0" description="暂时没有可用的服务器(下拉刷新)" />
        </van-pull-refresh>
    </van-list>
</template>

<style lang="less">
.GameServerList .van-pull-refresh {
    height: calc(100vh - 50px);
}
</style>
<script lang="ts">
import { defineComponent, ref } from "vue";
import { List, Cell, PullRefresh, Tag, Empty } from "vant";
import { GameServerInfo, IGameServerInfo } from "../assets/shared/gateClient/GameServer";
import { GateClient } from "../assets/shared/gateClient/gateClient";

const list = ref([] as GameServerInfo[]);
const error = ref(false);
const loading = ref(false);
const finished = ref(false);
const errorText = ref("");

export default defineComponent({
    name: "GameServerList",
    props: {
        gateClient: {
            type: GateClient,
            required: true,
        },
    },
    emits:{
        selectedserver:null,
    },
    components: {
        [List.name]: List,
        [Cell.name]: Cell,
        [PullRefresh.name]: PullRefresh,
        [Tag.name]: Tag,
        [Empty.name]: Empty,
    },
    data() {
        return {
            list,
            error,
            loading,
            finished,
            errorText,
        };
    },

    methods: {
        async onLoad(): Promise<void> {
            var serverListRet = await this.gateClient.getGameServers();
            loading.value = false;
            if (!serverListRet.isSucc) {
                errorText.value = "获取游戏服务器列表失败:" + serverListRet.err;
                error.value = true;
                return;
            }
            list.value = serverListRet.res.GameServerList;
            finished.value = true;
        },
        onSelectedServer(serverInfo: IGameServerInfo) {
            this.$emit("selectedserver", serverInfo);
        },
    },
});
</script>
